package com.tsugun.mediaplayer.presenter.utils

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Log

import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject

import java.io.BufferedReader
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.MalformedURLException
import java.net.URL
import java.net.URLConnection

import com.tsugun.mediaplayer.presenter.utils.LogHelper.TAG

/**
 * 网络请求工具类
 * Created by shize on 2017/8/9.
 */

object HttpJSONHelper {
    val START_URL = "http://artistpicserver.kuwo.cn/pic.web?type=" + "big_artist_pic&pictype=url&content=list&&id=0&name="
    val END_URL = "&from=android&json=1&version=1&width=1080&height=1920"
    val ARRAY_NAME = "array"
    val KEY = "key"

    /**
     * 解析json数据，获取图片地址
     */
    fun getImageURL(artist: String): URL? {
        var url: URL? = null
        try {
            val json = fetchJSONFromUrl(START_URL + artist + END_URL) ?: return null
            val jArray = json.getJSONArray(ARRAY_NAME)
            val jObject = jArray.opt(0) as JSONObject
            url = URL(jObject.getString(KEY))
        } catch (e: JSONException) {
            e.printStackTrace()
        } catch (e: MalformedURLException) {
            e.printStackTrace()
        }

        Log.d(TAG, "getImageURL: imageUrl = " + url!!)
        return url
    }

    /**
     * 从指定地址获取json

     * @param strUrl 地址
     * *
     * @throws JSONException json异常
     */
    @Throws(JSONException::class)
    private fun fetchJSONFromUrl(strUrl: String): JSONObject? {
        var reader: BufferedReader? = null
        try {
            val urlConnection = URL(strUrl).openConnection()
            reader = BufferedReader(InputStreamReader(
                    urlConnection.getInputStream(), "UTF-8"))
            val sb = StringBuilder()
            var line: String? = reader.readLine()
            while (line != null) {
                sb.append(line)
                line = reader.readLine()
            }
            return JSONObject(sb.toString())
        } catch (e: JSONException) {
            throw e
        } catch (e: Exception) {
            Log.e(TAG, "fetchJSONFromUrl: 获取json失败！", e)
            return null
        } finally {
            if (reader != null) {
                try {
                    reader.close()
                } catch (e: IOException) {
                    // ignore
                }

            }
        }
    }

    /**
     * 下载图片

     * @param url 图片地址
     * *
     * @return 图片bitmap
     */
    fun downloadBitmap(url: URL): Bitmap? {
        var bitmap: Bitmap? = null
        try {
            // 使用HttpURLConnection打开链接
            val connection = url.openConnection() as HttpURLConnection
            connection.doInput = true
            connection.connect()
            // 将得到的数据转化为InputStream
            val `is` = connection.inputStream
            // 再将InputStream转换为Bitmap
            bitmap = BitmapFactory.decodeStream(`is`)
            CloseHelper.closeQuietly(`is`)
        } catch (e: IOException) {
            e.printStackTrace()
        }

        return bitmap
    }
}
